<script setup lang="tsx">
import { defineComponent, h, nextTick, reactive, ref, watch } from 'vue';
import { NButton, NForm, NGradientText, NInput, NPopconfirm, NTag, useMessage } from 'naive-ui';
import type {
  CascaderOption,
  DataTableColumns,
  DataTableRowKey,
  DrawerPlacement,
  FormInst,
  NumberAnimationInst
} from 'naive-ui';
import {
  // fetchAddDetail,
  fetchBatchAddDetail,
  fetchDeleteBatchDetail,
  fetchDeleteDetail,
  fetchDeleteOrder,
  fetchEditDetail,
  fetchEditOrder,
  fetchGetAllDish,
  fetchGetDetailByID
} from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';

defineOptions({
  name: 'Detail'
});

interface Props {
  ordertitle: string;
  currentid: any;
  order: Api.Food.Order | undefined;
  currentSale: GLfloat;
}

const props_current = defineProps<Props>();

interface Emits {
  (e: 'closedd'): void;
  (e: 'onDeleted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const loading = defineModel<boolean>('loading', {
  default: false
});

function closeDrawer() {
  visible.value = false;
}

type Model = Pick<Api.Food.Detail, 'dish' | 'orders' | 'number' | 'price' | 'message'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    dish: '',
    orders: '',
    number: 1,
    price: 0,
    message: ''
  };
}

const appStore = useAppStore();
const disabled = ref(true);
const message = useMessage();
// 集联数据
const checkStrategyIsChild = ref(true);
const cascade = ref(true);
const showPath = ref(true);
const hoverTrigger = ref(true);
const filterable = ref(true);
const responsiveMaxTagCount = ref(true);
const clearFilterAfterSelect = ref(true);
const multiDetail = ref<string[]>();
const memLabel = ref({});
const dishlist = ref<Api.Food.DishList>();
// const dishOptions = ref<CommonType.Option<string>[]>([]);
const dishOptions2 = ref<CascaderOption[]>([]);
const currentdata = ref<Api.Food.DetailList>();
const totalPrice = ref(0); // 总价
const afterPrice = ref<GLfloat>(0.0); // 折后价
const retry = ref(0);
const 酒水Item = ref([]);
const 酒水不打折 = ref(0);
const ordercount = ref({});
const checkedRowKeys = ref<string[]>([]);
const checkedRowKeysRefDetail = ref<DataTableRowKey[]>([]);
const placement = ref<DrawerPlacement>('bottom');
const numberAnimationInstRef = ref<NumberAnimationInst | null>(null);
const formRef = ref<FormInst | null>(null);
const currentSelectOrderNew = ref<Api.Food.Order | null>(null);
// const rowKey = (row: Api.Food.Detail) => row.id;
const handleCheck = (rowKeys: DataTableRowKey[]) => {
  checkedRowKeysRefDetail.value = rowKeys;
};

function closedd() {
  emit('closedd');
}

async function getDish() {
  model.orders = props_current.currentid;
  const datas = await fetchGetAllDish();
  if (datas.error) {
    message.error(datas.error.message);
  } else {
    retry.value += 1;

    if (retry.value === 1) {
      dishOptions2.value = [];
      console.log('获取菜单 retry', retry.value);
      dishlist.value = datas.data;
      console.log('dishlist', dishlist.value);
      const tmp = new Map();
      datas.data.records?.forEach(item => {
        if (tmp.has(item.category)) {
          const tt = tmp.get(item.category);
          memLabel.value[item.id] = { name: item.name, kind: item.category };
          tt.push({
            label: `${item.name} ${item.short} ${item.price}`,
            value: item.id,
            disabled: item.disabled
          });
          tmp.set(item.category, tt);
        } else {
          memLabel.value[item.id] = { name: item.name, kind: item.category };
          tmp.set(item.category, [
            {
              label: `${item.name} ${item.short} ${item.price}`,
              value: item.id,
              disabled: item.disabled
            }
          ]);
        }
      });
      tmp.forEach((value, key) => {
        if (key === '酒水饮料') {
          酒水Item.value = value;
        }
        dishOptions2.value.push({
          // type: 'group',
          label: key,
          value: key,
          children: value
        });
      });
      console.log('dishOptions', dishOptions2.value);
    } else if (retry.value > 5) {
      console.log('使用缓存菜单 retry', retry.value);
      retry.value = 0;
      getDish();
    }
  }
  // getDishOptions();
}

function handleUpdateValue(value: string[], options: CascaderOption[]) {
  console.log(value, options);
  multiDetail.value = value;
  // model.dish = value;
}

function resets() {
  // model = {
  //   dish: '',
  //   orders: props_current.currentid,
  //   number: 1,
  //   price: 0,
  //   message: ''
  // };
  model.dish = '';
  multiDetail.value = [];
}

async function handleValidateClick() {
  console.log('ddd', model);

  // formData.value = {
  //   dish: String(formValue.value.dish),
  //   orders: String(formValue.value.orders),
  //   number: formValue.value.number,
  //   message: formValue.value.message
  // };

  const tmp = {
    dish: multiDetail.value?.join(),
    orders: String(props_current.currentid),
    number: model.number,
    message: model.message
  };
  const datas = await fetchBatchAddDetail(tmp);
  if (datas.error) {
    message.error('添加菜单失败');
  } else {
    message.success('添加菜单成功');
    refreshDetail();
    resets();
  }
}

// async function getDataDetail() {
//   console.log('3');
//   const datas = await fetchGetDetailByID(props_current.currentid);
//   if (datas.error) {
//     message.error(`code: ${datas.error.response?.status} 错误信息：${datas.error.response?.data.msg}`);
//   }

//   if (datas.data !== null) {
//     currentdata.value = datas.data;
//     console.log('datas.log', datas.data);
//   }
// }

async function handleBatchDeleteDetail() {
  console.log(checkedRowKeysRefDetail.value);
  const ids: string[] = [];
  checkedRowKeysRefDetail.value.forEach(id => {
    ids.push(id.toString());
  });

  const datas = await fetchDeleteBatchDetail(ids);
  if (!datas.error) {
    window.$message?.success($t('common.deleteSuccess'));
    console.log(datas.error);
  } else {
    window.$message?.error(datas.error.message);
  }
  //   console.log(checkedRowKeys.value);

  refreshDetail();
}

async function handleDeleteDetail(id: string) {
  const datas = await fetchDeleteDetail(id);
  if (datas.error) {
    message.error(`删除订单菜品失败 ${datas.error.response?.data.msg}`);
  }

  refreshDetail();
}

async function refreshDetail() {
  const datas = await fetchGetDetailByID(props_current.currentid);
  if (datas.error) {
    if (datas.error.response?.status === 404) {
      message.warning(`桌号 ${props_current.currentid} 还未点菜`);
    } else {
      message.error(`code: ${datas.error.response?.status} 错误信息：${datas.error.response?.data.msg}`);
    }
  }
  // console.log('detail id ', props_current.currentid, datas);
  ordercount.value = datas.data.ordercount.count;
  // totalPrice.value = 0;
  // afterPrice.value = 0;
  // 酒水不打折.value = 0;
  // console.log('酒水不打折', 酒水Item.value);
  if (datas.data.records !== null) {
    currentdata.value = datas.data;
    // const lllength = currentdata.value?.records.length;
    // currentdata.value.records.forEach((item, index) => {
    //   let status = false;
    //   currentdata.value.records[index].id2 = lllength - index;
    //   // console.log('123333', 酒水Item.value);
    //   // 酒水Item.value.forEach(item2 => {
    //   //   // console.log('11111', item.dish, item2.value, item.dish === String(item2.value));
    //   //   if (item.dish === String(item2.value)) {
    //   //     // console.log('2222', item, item2);
    //   //     status = true;
    //   //   }
    //   // });
    //   // if (status) {
    //   //   酒水不打折.value += item.price;
    //   // } else {
    //   //   totalPrice.value += item.price;
    //   // }
    // });
    // afterPrice.value = totalPrice.value * props_current.currentSale;
  } else {
    // console.log('3333 delete currentdata');
    currentdata.value = null;
  }
  loading.value = true;
  nextTick().then(() => {
    loading.value = false;
  });
  console.log('currentdata', currentdata.value, afterPrice.value, totalPrice.value, 酒水不打折.value);
}

const page = ref(1);

const handlePageChange = curPage => {
  page.value = curPage;
};

const getDataIndex = key => {
  return currentdata.value.records.findIndex(item => item.id === key);
};

const ShowOrEdit = defineComponent({
  props: {
    value: [String, Number],
    onUpdateValue: [Function, Array]
  },
  setup(props) {
    const isEdit = ref(false);
    const inputRef = ref(null);
    const inputValue = ref(props.value);
    function handleOnClick() {
      isEdit.value = true;
      nextTick().then(() => {
        inputRef.value.focus();
      });
    }
    function handleChange() {
      props.onUpdateValue(inputValue.value);
      isEdit.value = false;
    }
    function handleBlur() {
      isEdit.value = false;
    }
    return () =>
      h(
        'div',
        {
          style: 'min-height: 22px',
          onClick: handleOnClick
        },
        isEdit.value
          ? h(NInput, {
              ref: inputRef,
              value: inputValue.value,
              onUpdateValue: v => {
                inputValue.value = v;
              },
              onChange: handleChange,
              onBlur: handleBlur
            })
          : props.value
      );
  }
});

async function handleDeleteOrder() {
  const { error, data } = await fetchDeleteOrder(props_current.currentid);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    console.log(data);
  } else {
    window.$message?.error(error.message);
  }
  //   onDeleted();
  emit('onDeleted');
}

async function handleSubmit() {
  // 准备数据
  console.log('handleSubmit', props_current.order);
  currentSelectOrderNew.value = props_current.order;
  currentSelectOrderNew.value.price =
    ordercount.value.酒水饮料 + ordercount.value.基础消费 + ordercount.value.菜品消费未打折;
  currentSelectOrderNew.value.afterprice =
    ordercount.value.酒水饮料 + ordercount.value.基础消费 + ordercount.value.菜品消费;
  currentSelectOrderNew.value.current = '已结账';
  currentSelectOrderNew.value.id = props_current.currentid;

  const datas = await fetchEditOrder(props_current.currentid, currentSelectOrderNew.value);
  if (datas.error) {
    message.error(datas.error.message);
  } else {
    // dishactive.value = false;
    emit('closedd');
    message.success(`结账成功 ${datas.data}`);
  }
  closeDrawer();
  message.success(`结账成功`);
}

function handlePositiveClick() {
  handleDeleteOrder();
  //   dishactive.value = false;
  emit('closedd');
  message.info('已删除订单');
  refreshDetail();
}

function handleNegativeClick() {
  message.info('已取消');
}

const columesDish: DataTableColumns<Api.Food.Detail> = [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'id2',
    title: '序号',
    align: 'center',
    width: 64
  },
  {
    key: 'dish',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'info'
        },
        { default: () => '菜品' }
      );
    },
    align: 'center',
    width: 64,
    render: row => {
      const tmp = memLabel.value[row.dish];
      if (tmp !== undefined) {
        // console.log('memLabel', tmp, tmp.name);
        return <NTag type="info">{tmp.name}</NTag>;
      }
      return row.dish;
    }
  },
  {
    key: 'kind',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'danger'
        },
        { default: () => '类型' }
      );
    },
    align: 'center',
    width: 64,
    render: row => {
      const tmp = memLabel.value[row.dish];
      if (tmp !== undefined) {
        return <NTag type="success">{tmp.kind}</NTag>;
      }
      return row.dish;
    }
  },
  {
    key: 'price',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'warning'
        },
        { default: () => '价格' }
      );
    },
    align: 'center',
    width: 64
    // render: row => {
    //   return <NTag type="error">{row.price}</NTag>;
    // }
  },
  {
    key: 'number',
    title: '数量',
    align: 'center',
    width: 64,
    render(row) {
      const index = getDataIndex(row.id);
      if (props_current.order.current === '已结账') {
        return row.number;
      }
      return h(ShowOrEdit, {
        value: String(row.number),
        async onUpdateValue(v) {
          currentdata.value.records[index].number = Number(v);
          // 发起修改
          const datas = await fetchEditDetail(row.id, currentdata.value.records[index]);
          if (datas.error) {
            message.error(`修改订单菜品失败 ${datas.error.message}`);
          }
          refreshDetail();
        }
      });
    }
  },
  {
    key: 'message',
    title: '备注',
    align: 'center',
    width: 180
  },
  {
    key: 'times',
    title: '下单时间',
    align: 'center',
    width: 200,
    render: row => {
      return row.times.split('+')[0];
    }
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    width: 130,
    render: row => (
      <div class="flex-center gap-8px">
        {/* <NButton type="warning" ghost size="small" onClick={() => actived('bottom', row.id)}>
            {$t('common.order')}
          </NButton> */}
        {/* <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
          {$t('common.edit')}
        </NButton> */}
        <NPopconfirm onPositiveClick={() => handleDeleteDetail(row.id)}>
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
];

const rules = {
  dish: {
    required: true,
    message: '请选择菜品',
    trigger: 'blur'
  },
  order: {
    required: true,
    message: '请输入订单号',
    trigger: 'blur'
  }
};

function finshed() {
  message.success('上传成功');
  refreshDetail();
}

watch(visible, () => {
  if (visible.value) {
    getDish();
    // getDataDetail();
    refreshDetail();
  }
});
</script>

<template>
  <!-- 订单菜品详情 -->
  <NDrawer v-model:show="visible" default-height="720" resizable :placement="placement">
    <NDrawerContent :title="props_current.ordertitle" closable>
      <NCard :title="$t('common.search')" :bordered="false" size="small" class="card-wrapper">
        <NForm ref="formRef" :model="model" :rules="rules" label-placement="top" :label-width="80">
          <NGrid responsive="screen" item-responsive>
            <!--
 <NFormItemGi span="24 s:12 m:6" label="订单" path="orders" class="pr-24px">
              <NInput v-model:value="model.orders" :disabled="disabled" placeholder="订单" />
            </NFormItemGi> 
-->
            <NFormItemGi span="24 s:12 m:8" label="菜品" path="status" class="pr-24px">
              <NCascader
                v-model:value="multiDetail"
                multiple
                clearable
                placeholder="请选择菜品"
                :max-tag-count="responsiveMaxTagCount ? 'responsive' : undefined"
                :expand-trigger="hoverTrigger ? 'hover' : 'click'"
                :options="dishOptions2"
                :cascade="cascade"
                :check-strategy="checkStrategyIsChild ? 'child' : 'all'"
                :show-path="showPath"
                :filterable="filterable"
                :clear-filter-after-select="clearFilterAfterSelect"
                @update:value="handleUpdateValue"
              />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:8" label="数量" path="number" class="pr-24px">
              <NInputNumber v-model:value="model.number" placeholder="数量" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:8" label="备注" path="message" class="pr-24px">
              <NInput v-model:value="model.message" placeholder="备注" />
            </NFormItemGi>
            <NFormItemGi span="24 m:24" class="pr-24px">
              <NSpace class="w-full" justify="space-around" size="large">
                <NButton @click="refreshDetail">
                  <template #icon>
                    <icon-ic-round-refresh class="text-icon" />
                  </template>
                  刷新
                </NButton>
                <NButton
                  type="primary"
                  :disabled="multiDetail?.length === 0 ? true : false"
                  ghost
                  @click="handleValidateClick"
                >
                  <template #icon>
                    <icon-ic-round-add class="text-icon" />
                  </template>
                  添加
                </NButton>
                <NButton @click="resets">
                  <template #icon>
                    <icon-ic-round-refresh class="text-icon" />
                  </template>
                  {{ $t('common.reset') }}
                </NButton>
                <NUpload :action="`/apis/v1/${props_current.currentid}/detail/upload`" @finish="finshed">
                  <template #icon>
                    <icon-ic-round-upload class="text-icon" />
                  </template>
                  <NButton type="info">表格上传</NButton>
                </NUpload>
                <NButton
                  type="error"
                  :disabled="checkedRowKeys.length === 0 ? true : false"
                  @click="handleBatchDeleteDetail"
                >
                  <template #icon>
                    <icon-ic-round-delete class="text-icon" />
                  </template>
                  批量删除
                </NButton>
              </NSpace>
            </NFormItemGi>
          </NGrid>
        </NForm>
      </NCard>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        striped
        :columns="columesDish"
        :data="currentdata?.records"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        class="sm:h-full"
        :on-update:page="handlePageChange"
        @update:checked-row-keys="handleCheck"
      />
      <template #footer>
        <NSpace :size="16">
          <NStatistic label="基础消费" tabular-nums>
            <NNumberAnimation ref="numberAnimationInstRef" :from="0" :to="ordercount.基础消费" />
            <template #prefix>¥</template>
          </NStatistic>
          <NStatistic label="酒水总价(不打折)" tabular-nums>
            <NNumberAnimation ref="numberAnimationInstRef" :from="0" :to="ordercount.酒水饮料" />
            <template #prefix>¥</template>
          </NStatistic>
          <NStatistic :label="`菜品折后价 / 总价【${currentSale}】`" tabular-nums>
            <NNumberAnimation ref="numberAnimationInstRef" :from="0" :to="ordercount.菜品消费" :precision="2" />
            <template #prefix>¥</template>
            <template #suffix>/ {{ ordercount.菜品消费未打折 }}</template>
          </NStatistic>
          <NStatistic label="应付总价" tabular-nums>
            <NNumberAnimation
              ref="numberAnimationInstRef"
              :from="0"
              :to="ordercount.酒水饮料 + ordercount.基础消费 + ordercount.菜品消费"
              :precision="2"
            />
            <template #prefix>¥</template>
          </NStatistic>
          <NButton size="large" @click="closedd">{{ $t('common.cancel') }}</NButton>
          <!-- <NButton @click="handleDeleteOrder">{{ $t('common.cancel') }}</NButton> -->
          <NPopconfirm @positive-click="handlePositiveClick" @negative-click="handleNegativeClick">
            <template #trigger>
              <NButton size="large" type="error">删除</NButton>
            </template>
            是否删除当前订单？
          </NPopconfirm>
          <NPopconfirm @positive-click="handleSubmit" @negative-click="handleNegativeClick">
            <template #trigger>
              <NButton size="large" type="success">结账</NButton>
            </template>
            是否结束当前订单？
          </NPopconfirm>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
